package com.itheima.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码
     *
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R sengMsg(@RequestBody User user) {

        //获取用户的手机号
        String phone = user.getPhone();

        //判断手机号是否为空
        if (StringUtils.isEmpty(phone)) {
            return R.error("手机号不能为空");
        }

        //利用工具类生成数字验证码
        String code = RandomUtil.randomNumbers(4);
        //String code = ValidateCodeUtils.generateValidateCode4String(4);
        log.info("验证码是:{}", code);

        //调用阿里云的短信服务,发送验证码短信
        //String code = "8889";
        //SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,code);
        //log.info("验证码是:{}", code);
        //session.setAttribute(phone, code);

        //Redis优化,将生产的验证码缓存到Redis中,并设置有效期5分钟
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("code:" + phone, code, 5l, TimeUnit.MINUTES);

        return R.success("验证码发送成功");
    }

    /**
     * 用户登录
     *
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R userLogin(@RequestBody Map map, HttpSession session) {
        //获取手机号和验证码
        String phone = (String) map.get("phone");
        String code = (String) map.get("code");

        //获取发送出去的验证码及手机号
        //获取session的key
        //Object sendCode = session.getAttribute(phone);

        //从Redis中获取验证码
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String loginCode = (String) valueOperations.get("code:" + phone);

        //验证码是否一致
        if (loginCode.equals(code)) {
            //查询user表中是否有此用户
            LambdaUpdateWrapper<User> lqw = new LambdaUpdateWrapper<>();
            lqw.eq(User::getPhone, phone);
            User user = userService.getOne(lqw);
            //判断该登录用户是否注册
            if (user == null) {
                //没有注册,则自动注册
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user", user);
            //session.removeAttribute(phone);
            redisTemplate.delete("code:" + phone);
            return R.success("登陆成功");
        }

        return R.error("手机号或验证码错误,登陆失败");
    }

    /**
     * 退出登录
     *
     * @param session
     * @return
     */
    @PostMapping("/loginout")
    public R loginout(HttpSession session) {

        session.removeAttribute("user");

        return R.success("退出成功");
    }

}
